<!DOCTYPE html>
<html lang="zh_CN">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"
    />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no" />
    <meta http-equiv="pragma" content="no-cache" />
    <meta http-equiv="cache-control" content="no-cache" />
    <meta http-equiv="expires" content="0" />

    <title></title>
    <link rel="stylesheet" type="text/css" href="/chat/wxchat/static/css/mui.min.css" />
    <link rel="stylesheet" type="text/css" href="/chat/wxchat/static/css/mui.imageviewer.css" />
    <link rel="stylesheet" type="text/css" href="/chat/wxchat/static/css/chat-im.css?v=3444646" />
    <style type="text/css">
        #upImage {
            cursor: pointer;
        }

        .qjs-backdrop {
            position: fixed;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            z-index: 998;
            background-color: rgba(0, 0, 0, .1);
            display: none;
        }

        .loadEffect {
            width: 4.266666666666667rem;
            height: 4.266666666666667rem;
            position: relative;
            margin: 0 auto;
            margin-top: 60%;
        }

        .loadEffect span {
            display: inline-block;
            width: 0.6826666666666666rem;
            height: 0.6826666666666666rem;
            border-radius: 50%;
            background: #222;
            position: absolute;
            -webkit-animation: load 1.04s ease infinite;
        }

        @-webkit-keyframes load {
            0% {
                opacity: 1;
            }
            100% {
                opacity: 0.3;
            }
        }

        .loadEffect span:nth-child(1) {
            left: 0;
            top: 50%;
            margin-top: -0.3413333333333333rem;
            -webkit-animation-delay: 0.13s;
        }

        .loadEffect span:nth-child(2) {
            left: 0.5973333333333334rem;
            top: 0.5973333333333334rem;
            -webkit-animation-delay: 0.26s;
        }

        .loadEffect span:nth-child(3) {
            left: 50%;
            top: 0;
            margin-left: -0.3413333333333333rem;
            -webkit-animation-delay: 0.39s;
        }

        .loadEffect span:nth-child(4) {
            top: 0.5973333333333334rem;
            right: 0.5973333333333334rem;
            -webkit-animation-delay: 0.52s;
        }

        .loadEffect span:nth-child(5) {
            right: 0;
            top: 50%;
            margin-top: -0.3413333333333333rem;
            -webkit-animation-delay: 0.65s;
        }

        .loadEffect span:nth-child(6) {
            right: 0.5973333333333334rem;
            bottom: 0.5973333333333334rem;
            -webkit-animation-delay: 0.78s;
        }

        .loadEffect span:nth-child(7) {
            bottom: 0;
            left: 50%;
            margin-left: -0.3413333333333333rem;
            -webkit-animation-delay: 0.91s;
        }

        .loadEffect span:nth-child(8) {
            bottom: 0.5973333333333334rem;
            left: 0.5973333333333334rem;
            -webkit-animation-delay: 1.04s;
        }

        .im-chat-text .previewImage {
            cursor: pointer;
            min-width: 2.1333333333333333rem;
            min-height: 2.1333333333333333rem;
        }

        /* 改写用户图像与消息顶部对齐 */

        .im-chat-user img {
            margin-top: 1.1093333333333333rem;
        }

        /* 消息箭头 */

        .im-chat-text:after {
            left: -1rem;
            top: 0.3rem;
            transform: rotate(90deg);
            -webkit-transform: rotate(90deg);
            -moz-transform: rotate(90deg);
            -ms-transform: rotate(90deg);
            -o-transform: rotate(90deg);
        }

        .im-chat-mine .im-chat-text:after {
            right: -1rem;
            transform: rotate(270deg);
            -webkit-transform: rotate(270deg);
            -moz-transform: rotate(270deg);
            -ms-transform: rotate(270deg);
            -o-transform: rotate(270deg);
        }

        /* 消息框右移 */

        .im-chat-main ul .im-chat-mine {
            padding-right: 2.304rem;
        }

        .im-chat-main ul li {
            padding-left: 2.304rem;
        }

        .im-chat-main ul {
            overflow-y: scroll;
        }

        #sendMessage {
            z-index: 9999;
        }

        /* iconfont 字体图标 */

        @font-face {
            font-family: 'gtmc_chat';
            src: url('/chat/wxchat/static/fonts/iconfont.eot');
            src: url('/chat/wxchat/static/fonts/iconfont.eot?#iefix') format('embedded-opentype'),
            url('/chat/wxchat/static/fonts/iconfont.woff') format('woff'),
            url('/chat/wxchat/static/fonts/iconfont.ttf') format('truetype'),
            url('/chat/wxchat/static/fonts/iconfont.svg#gtmc_chat') format('svg');
        }

        .gtmc_chat {
            font-family: "gtmc_chat" !important;
            font-size: 1.3rem;
            font-style: normal;
            color: gray;
            -webkit-font-smoothing: antialiased;
            -webkit-text-stroke-width: 0.008533333333333334rem;
            -moz-osx-font-smoothing: grayscale;
        }
    </style>
</head>

<body contextmenu="return false;">
    <div class="qjs-backdrop">
        <div class="loadEffect">
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
        </div>
    </div>

    <div class="im-chat-main">
        <ul id="msg_list">
        </ul>

    </div>
    <!-- 底部 -->
    <footer id="footer">
        <!--<div class="footer-left">
            <i class="mui-icon chat-icon chat-icon-voice"></i>
        </div>-->
        <div class="footer-center">
            <textarea id="msg_text" type="text" class="input-text"></textarea>

            <!--
            <div class="mui-btn mui-btn-outlined voice-btn">按住 说话</div>
            -->
        </div>
        <div class="footer-right">
            <!--
            <i class="mui-icon chat-icon chat-icon-face" style="margin-right: 0.2rem; padding-left: 0.4266666666666667rem;"></i>
           -->
            <!-- <i class="gtmc_chat emoticon" alt="表情包">&#xe6c0;</i>
            <i class="gtmc_chat dialogue" alt="常见对白">&#xe60d;</i>
            <i class="gtmc_chat chat-icon-add-more" alt="添加">&#xe61e;</i> -->

            <div class="gtmc_chat emoticon" alt="表情包">&#xe6c0;</div>
            <div class="gtmc_chat dialogue" alt="常见对白">&#xe60d;</div>
            <div class="gtmc_chat chat-icon-add-more" alt="添加">&#xe61e;</div>


            <!--<i class="mui-icon chat-icon chat-icon-add-more"></i>-->

            <button class="mui-btn mui-btn-success mui-hidden" id="sendMessage">发送</button>
        </div>
    </footer>
    <!-- 表情包 -->
    <div class="Emoji">
        <div id="slider" class="mui-slider">
            <div class="mui-slider-group">
                <!-- 站位页数 -->
                <div class="mui-slider-item"></div>
                <div class="mui-slider-item"></div>
                <div class="mui-slider-item"></div>
                <div class="mui-slider-item"></div>
            </div>
            <div class="mui-slider-indicator point" style="marginTop: -0.4266666666666667rem;">
                <div class="mui-indicator mui-active"></div>
                <div class="mui-indicator"></div>
                <div class="mui-indicator"></div>
                <div class="mui-indicator"></div>
            </div>
        </div>
    </div>
    <!-- 常用对白/内容库 -->
    <div class="simple">
        <div class="simple_tit">
            <span class="simple_often simple_check">常见对白</span>
            <span class="simple_many">常见内容库</span>
        </div>
        <!-- 常见对白 -->
        <div class="often_list" id="often_list">
            <!-- <p>
                <i class="gtmc_chat many_three_point" alt="点">&#xe600;</i>
                <span>匹配的内容</span>
            </p> -->
        </div>
        <script id="oftenList" type="text/html">
            {{each list as value i}}
                <p>
                    <i class="gtmc_chat many_three_point" alt="点">&#xe600;</i>
                    <span data-id="{{value.id}}">{{value.content}}</span>
                </p>                    
            {{/each}}
        </script>

        <!-- 常见内容库 -->
        <div class="many_list" id="many_list">
            <div class="many_one">
                <p>
                    <i class="gtmc_chat many_one_arrow" alt="箭头">&#xe603;</i>
                    <span>一级标签分类</span>
                </p>
                <div class="many_two">
                    <p>
                        <i class="gtmc_chat many_two_add" alt="加号">&#xe602;</i>
                        <span>二级分类标签</span>
                    </p>
                    <div class="many_three">
                        <p>
                            <i class="gtmc_chat many_three_point" alt="点">&#xe600;</i>
                            <span>需要什么帮助么?</span>
                        </p>
                    </div>
                </div>
            </div>

        </div>

        <script id="manyList" type="text/html">
            {{each list as value index}}
            <div class="many_one">
                <p>
                    <i class="gtmc_chat many_one_arrow" alt="箭头">&#xe603;</i>
                    <span>{{value.firstName}}</span>
                </p>
                {{if value.children}}
                    {{each value.children as val id}}
                    <div class="many_two">
                        <p>
                            <i class="gtmc_chat many_two_add" alt="加号">&#xe602;</i>
                            <span>{{val.secondName}}</span>
                        </p>
                        {{if val.contents}}
                            {{each val.contents as v i}}
                            <div class="many_three">
                                <p>
                                    <i class="gtmc_chat many_three_point" alt="点">&#xe600;</i>
                                    <span>{{v}}</span>
                                </p>
                            </div>
                            {{/each}}
                        {{/if}}
                    </div>
                    {{/each}}
                {{/if}}
            </div>                   
            {{/each}}
        </script>

    </div>
    <!-- 更多弹出内容 -->
    <div class="mui-content more-content">
        <ul class="mui-table-view mui-grid-view mui-grid-9">
            <li class="mui-table-view-cell mui-media mui-col-xs-3 mui-col-sm-3" id="upImage" data-type="images">
                <span class="mui-icon mui-icon-image"></span>
                <div class="mui-media-body">图片</div>
            </li>
            <!--
            <li class="mui-table-view-cell mui-media mui-col-xs-3 mui-col-sm-3">
                <span class="mui-icon mui-icon-eye"></span>
                <div class="mui-media-body">小视频</div>
            </li>
            <li class="mui-table-view-cell mui-media mui-col-xs-3 mui-col-sm-3">
                <span class="mui-icon mui-icon-location"></span>
                <div class="mui-media-body">位置</div>
            </li>
            <li class="mui-table-view-cell mui-media mui-col-xs-3 mui-col-sm-3">
                <span class="mui-icon mui-icon-contact"></span>
                <div class="mui-media-body">名片</div>
            </li>
            -->
        </ul>
    </div>
</body>

<!-- 聊列表模板 -->
<script id="list" type="text/html">
    <div class="fade-in">
    {{each list as value i}} 

    {{if value.time}}
    <div class="recording_time">
        <span>{{value.time}}</span>
    </div>
    {{else if value.direction==1}}
    <li class="lili">
        <div class="im-chat-user">
            {{if customer.ownerIcon}}
            <img class="mui-media-object mui-pull-left" src="{{customer.ownerIcon}}"></img>
            {{else}}
            <img class="mui-media-object mui-pull-left" src="/chat/wxchat/static/images/demo6.png"></img>
            {{/if}}
            <!-- <cite>{{customer.ownerName}}<i>{{value.crtTime}}</i></cite> -->
        </div>
        <div class="im-chat-text" id="chat-text{{1}}" >
            {{if value.imgFlag==1}}
            <img class="previewImage" src="{{value.content}}"/> 
            {{else}} 
                <span>
                    {{value.content}} 
                </span>
            {{/if}}
        </div>
    </li>
    {{else if value.direction==0}}
    <li class="im-chat-mine">
        <div class="im-chat-user">
            <img src="{{user.iconsPhoto}}" />
            <!-- <cite><i>{{value.crtTime}}</i>{{user.weixinName}}</cite> -->
        </div>
        <div class="im-chat-text" id="chat-text{{1}}">
            {{if value.imgFlag==1}}
            <img class="previewImage" src="{{value.content}}" /> 
            {{else}} 
                <span>
                {{value.content}}   
                </span>
            {{/if}}
        </div>
    </li>
    {{/if}} 
    
    {{/each}}
</div>
</script>
<script src="/chat/wxchat/static/js/jquery-2.2.4.min.js"></script>
<script src="/chat/wxchat/static/js/mui.min.js"></script>
<script src="/chat/wxchat/static/js/rem.js"></script>
<script src="/chat/wxchat/static/js/mui.imageViewer.js"></script>
<script src="/chat/wxchat/static/js/template.js"></script>
<script src="/chat/wxchat/message/jmessage-sdk-web.min.js"></script>
<script src="/chat/wxchat/static/js/common.js?v=05110"></script>
<script src="/chat/wxchat/static/js/myStorage.js"></script>
<script src="/chat/wxchat/static/js/clipboard.min.js"></script>
<script src="https://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>

<script th:inline="javascript">

    var msgList = document.getElementById("msg_list");
    var boxMsgText = document.getElementById("msg_text");
    var id = [[${userId }]];
    var code = [[${ownerCode }]];
    var wxCode = [[${wxCode }]];
    var dealerCode = [[${dealerCode }]];
    var result = new Object();
    var currPage = 1;
    var sizePage = 5;
    var wxAuth = false;
    var msgIdFlag = true;
    var msgId = new Array();
    var images = {
        localId: [],
        serverId: []
    };
    var sendFlag = true;
    var lastTime = new Date().getTime();

    var inputTextBox = document.getElementById('footer');
    mui.init();
    var messFlag = true;
    var imageLock = false;
    var oftenData = {};
    var manyData = {};
    var manyListData = [];
    var memoryData = [];
    var isOpenOften = true;
    var sessionObjCode = 0;
    var lastTime = 0;
    var isLastTime = false;

    sessionStorage.removeItem('ssssssss12');
    /*<![CDATA[*/
    (function ($) {
        window.addEventListener("swipedown", function (evt) {
            stopBubble(evt);
            stopDefault(evt);
            var y = msgList.scrollTop;
            if (messFlag) {
                if (y < 20) {
                    messFlag = false;
                    addChat(currPage, sizePage, code, id);
                    bindImage(".im-chat-text .previewImage");
                }
            }
        });
    })(mui);

    // 常见对白接口请求
    $.ajax({
        type: "post",
        dataType: "json",
        traditional: true,
        data: { dealerCode: dealerCode },
        async: false,
        url: "/chat/wx/getWxChatDialogue",
        success: function (result) {
            if (result.data) {
                oftenData = { list: result.data }
                memoryData = result.data
                document.getElementById('often_list').innerHTML = template('oftenList', oftenData);
                setTimeout(function () {
                    oftenAddClick()
                }, 100)

            }
        },
        error: function (e) {
            imageLock = true;
            mui.toast("网络异常");
        }
    });

    // 常见内容接口
    $.ajax({
        type: "post",
        dataType: "json",
        traditional: true,
        data: { dealerCode: dealerCode },
        async: false,
        url: "/chat/wx/getWxChatContent",
        success: function (result) {
            if (result.data) {
                manyData = { list: result.data };
                manyListData = result.data;
                document.getElementById('many_list').innerHTML = template('manyList', manyData);
                setTimeout(function () {
                    manyAddClick();
                }, 0)
            }
        },
        error: function (e) {
            imageLock = true;
            mui.toast("网络异常");
        }
    });


//    var ar = [
//     {
//         "firstName": "1这是第一个一级标签",
//         "children": [
//           {
//             "contents": [
//               "3C3C内容",
//               "3C8C内容",
//               "这"
//             ],
//             "secondName": "2这是第一个二级标签"
//           },
//           {
//             "secondName": "2这是第一个二级标签"
//           },
//           {
//             "contents": [
//               "看"
//             ],
//             "secondName": "3这是第一个二级标签"
//           }
//         ]
//       },
//       {
//         "firstName": "1这是第二个一级标签",
//         "children": [
//           {
//             "contents": [
//               "EEEEEEEEEEEEEEEEEEEEEEEERRRRRRRRRTWETWERTEWTWERTTTTTTTTTTTTTTTTTTTTWERTWERTEWTEWR内容",
//               "是"
//             ],
//             "secondName": "2这第二个二级标签"
//           },
//           {
//             "contents": [
//               "5C什么内容"
//             ],
//             "secondName": "3这是第二个二级标签"
//           }
//         ]
//       },

//       ];
//      manyData = { list: ar };
//       manyListData = ar;
//     document.getElementById('many_list').innerHTML = template('manyList', manyData);

//     oftenData = { list: [{id:1,content:"哈哈"},{id:1,content:"这是"},{id:1,content:"什么"}] }
//     memoryData = [{id:1,content:"哈哈"},{id:1,content:"这是"},{id:1,content:"什么"}]
//     document.getElementById('often_list').innerHTML = template('oftenList', oftenData);





    /*]]>*/
    var cursorPositon = 0;
    $(function () {

        var b = isWx();
        if (b == 1) {
            //window.location.href="https://www.baidu.com";
        }
        var url = checkOs(code, id, wxCode);
        $.ajax({
            type: "post",
            dataType: "json",
            traditional: true,
            data: { userId: id, ownerCode: code, url: url },
            async: false,
            url: "/chat/wx/wx_chat_userInfo",
            success: function (data, textStatus) {
                imageLock = true;
                if (data) {
                    if (data.returnFlag == 1) {
                        result.user = data.data.user;
                        result.customer = data.data.customer;
                        result.auth = data.data.auth;
                        result.jsAuth = data.data.jsAuth;
                        var name = result.customer.ownerName;
                        var title;
                        sessionObjCode = result.customer.ownerCode;
                        // 读取缓存
                        getLocal(sessionObjCode);
                        if (name) {
                            title = name + '(' + result.customer.ownerCode + ')';
                        } else {
                            title = result.customer.ownerCode;
                        }
                        document.title = title;
                        weixin();
                    } else {
                        mui.toast(data.errorMsg);
                    }
                }
            },
            error: function (e) {
                imageLock = true;
                mui.toast("网络异常");
            }
        });
        addChat(currPage, sizePage, code, id);
        bindImage(".im-chat-text .previewImage");
        /*<![CDATA[*/
        //输入框事件绑定
        $("#msg_text").on({
            "keydown": function (e) {
                var that = this;
                if (e.ctrlKey && e.keyCode == 13) {
                    sendMsg(that.val(), 0);
                }
            },
            "keyup": function () {
            },
            "input propertychange": function (e) {
                showSendBtn();
                cursorPositon = e.target.selectionStart
                if ($('.often_list').css('display') != 'none') {
                    // 筛选常见对白
                    filterOften();
                } else {
                    // 筛选常见内容库
                    filterMany();

                }

                var isOpenOften = ($('.simple').css('display') != 'none');
                if (isOpenOften && $("#msg_text").val().trim()) {
                    oftenAddClick()
                }

                // 聊天缓存
                setLocal();
                this.scrollTop = this.scrollHeight;

            },
            "input": function (e) {
                cursorPositon = e.target.selectionStart
                if ($('.often_list').css('display') != 'none') {
                    // 筛选常见对白
                    filterOften();
                } else {
                    // 筛选常见内容库
                    filterMany();
                }

                var isOpenOften = ($('.simple').css('display') != 'none');
                if (isOpenOften && $("#msg_text").val().trim()) {
                    oftenAddClick()
                }
                // 聊天缓存
                setLocal();
                this.scrollTop = this.scrollHeight;

            },
            "change": function (e) {
                window.scrollTo(0, document.body.scrollHeight);
            },
            "click": function (e) {
                cursorPositon = e.target.selectionStart;

                if ($(".Emoji").css('display') === 'none' && $(".simple").css('display') === 'none') {
                    if ($(".more-content").css('display') === 'none') {
                        $('.simple').show();
                        $('#footer').css('bottom', '8.533333333333333rem');
                        $('.im-chat-main').css('paddingBottom', '11.093333333333334rem');
                        // 筛选常见对白
                        filterOften();
                        // var reg = $(this).val();
                        // var arr = [];
                        // if ($('.often_list').css('display') != 'none') {
                        //     $.each(memoryData, function (i, v) {
                        //         if (v.content.indexOf(reg) != -1) {
                        //             arr.push(v)
                        //         }
                        //     })
                        //     oftenData.list = arr
                        // } else {
                        //     oftenData.list = memoryData
                        // }
                        // document.getElementById('often_list').innerHTML = template('oftenList', oftenData);
                        // oftenAddClick()
                    }

                }
                e.stopPropagation();
            },
            "focus": function (e) {
                if ($(".more-content").css('display') != 'none') {
                    $(".more-content").hide();
                    $(".Emoji").hide();

                    $("footer").css("bottom", "0" + "px");
                    $(".im-chat-main").css("padding-bottom", "2.1333333333333333rem");
                    window.scrollTo(0, document.body.scrollHeight);
                }

            },
            "blur": function () {
                window.scrollTo(0, document.body.scrollHeight);
            },
            "tap": function (e) {
                $("#footer").on("tap", function (event) {
                    var sendMsgBtn = $(event.target);
                    if (sendMsgBtn.attr('id') == 'footer') {
                        $("#sendMessage").trigger('tap');
                    }
                })

                e.stopPropagation();
            }
        });
        /*]]>*/


        //表情按钮事件
        $(".footer-right i.chat-icon-face").unbind("tap")
        $(".footer-right i.chat-icon-face").on("tap", function (e) {
            var than = $(this);
            var footer = $("footer");

            //隐藏语音输入
            if ($(".footer-left i:first").hasClass("chat-icon-keyboard")) {
                $(".footer-center .voice-btn").hide();
                $(".footer-left i:first").attr("class", "mui-icon chat-icon chat-icon-voice");
                $("#msg_text").show();
                $("footer").css("padding-right", "2.7733333333333334rem");
                $(".footer-right").css("width", "4.266666666666667rem");
                $(".footer-right").css("right", "0.042666666666666665rem");
                $(".footer-center").css("padding-right", "1.0666666666666667rem");
                $(".footer-center").css("padding-left", "0.128rem");
                $(".footer-right i:first").show();
            }

            if (than.hasClass("chat-icon-keyboard")) {
                $(".face-content").hide();
                than.attr("class", "mui-icon chat-icon chat-icon-face");
                footer.css("bottom", "0");
                $(".im-chat-main").css("padding-bottom", "2.1333333333333333rem");
                setTimeout(function () {
                    $("#msg_text").focus();
                }, 10);
            } else {
                $(".more-content").hide();
                $(".face-content").show();
                than.attr("class", "mui-icon chat-icon chat-icon-keyboard");
                footer.css("bottom", $(".face-content").height());
                $(".im-chat-main").css("padding-bottom", $(".face-content").height() + 50);
            }

            document.getElementById("msg_list").scrollTop = msgList.scrollHeight + msgList.offsetHeight;
        });

        //绑定表情点击事件
        $(".face-content").find('.face-list>li').on('tap', function () {
            focusInsert(boxMsgText, 'face' + this.title + ' ');
            showSendBtn();
            document.getElementById("msg_list").scrollTop = msgList.scrollHeight + msgList.offsetHeight;
        });

        //更多按钮事件
        $(".footer-right .chat-icon-add-more").unbind("tap")
        $(".footer-right .chat-icon-add-more").on("tap", function (e) {
            var than = $(this);
            var footer = $("footer");

            //隐藏语音输入
            if ($(".footer-left i:first").hasClass("chat-icon-keyboard")) {
                $(".footer-center .voice-btn").hide();
                $(".footer-left i:first").attr("class", "mui-icon chat-icon chat-icon-voice");
                $("#msg_text").show();
                $("footer").css("padding-right", "2.7733333333333334rem");
                $(".footer-right").css("width", "4.266666666666667rem");
                $(".footer-right").css("right", "0.042666666666666665rem");
                $(".footer-center").css("padding-right", "1.0666666666666667rem");
                $(".footer-center").css("padding-left", "0.128rem");
                $(".footer-right i:first").show();
            }

            //为了美观把更多的高度设置成表情一样
            $(".more-content").height($(".face-content").height());

            //表情是展开的则隐藏
            if (than.prev().hasClass("chat-icon-keyboard")) {
                than.prev().attr("class", "mui-icon chat-icon chat-icon-face");
            }

            if ($(".more-content").css('display') != 'none') {
                $(".more-content").hide();
                footer.css("bottom", "0");
                $(".im-chat-main").css("padding-bottom", "2.1333333333333333rem");
            } else {
                $(".face-content").hide();
                $(".more-content").show();
                footer.css("bottom", $(".more-content").height());
                $(".im-chat-main").css("padding-bottom", $(".more-content").height() + 50);
            }

            document.getElementById("msg_list").scrollTop = msgList.scrollHeight + msgList.offsetHeight;
            $('.Emoji').hide();
            $('.simple').hide();
        });

        //录音按钮事件绑定
        $(".footer-center .voice-btn").on("tap", function () {
            mui.toast("该功能正在开发中，敬请期待");
        });



        /*<![CDATA[*/
        //发送按钮事件

        $("#footer").on("tap", function (event) {
            var sendMsgBtn = $(event.target);
            if (sendMsgBtn.attr('id') == 'footer') {

                $("#sendMessage").trigger('tap');
                //$("#msg_text").val('send-----');
            }
        })
        $("#sendMessage").on("tap", function () {
            var str = $("#msg_text").val();
            //var content = str.replace(/([\ud800-\udbff][\u0000-\uffff])/g,'');
            var content = str.trim();
            $("#msg_text").val(content);
            // var b = checkNull(content);
            if (!content) {
                // showSendBtn();
                mui.toast("内容不能为空");
                return !1;
            }
            if (sendFlag) {
                sendFlag = false;
            } else {
                return !1;
            }
            $(".qjs-backdrop").show();
            //调用后台接口
            var getTime = (new Date()).getTime();
            var sub = getTime - parseInt(lastTime);
            var html = "";
            var currentTime = getNowFormatDate();
            var requerD = { userId: id, ownerCode: code, content: content }
            if (sub > 300000) {
                html = '<div class="recording_time"><span>' + currentTime + '</span></div>';
                requerD.dateShow = 1;
            }
            var keyy = "fefe" + sub;

            $.ajax({
                type: "post",
                dataType: "json",
                traditional: true,
                data: requerD,
                async: true,
                url: "/chat/wx/wx_sendmessage",
                success: function (data, textStatus) {
                    sendFlag = true;
                    if (data) {
                        if (data.returnFlag == 1) {
                            html += '<li class="im-chat-mine">' +
                                '<div class="im-chat-user">' +
                                '<img src="' + result.user.iconsPhoto + '"/>' +
                                // '<cite><i>' + getNowFormatDate() + '</i>' + result.user.weixinName + '</cite>' +
                                '</div>' +
                                '<div class="im-chat-text"><span id=' + keyy + '>' + imContent($("#msg_text").val() || '&nbsp;') + '</span></div>' +
                                '</li>';
                            //追加内容
                            msgList.insertAdjacentHTML('beforeEnd', html);
                            lastTime = (new Date()).getTime();
                            //清空
                            $("#msg_text").val('')

                            // 缓存处理
                            var getLocal = JSON.parse(localStorage.getItem("chatInputRecord"));
                            var local = []
                            $.each(getLocal, function (i, v) {
                                if (v.code != sessionObjCode) {
                                    local.push(v)
                                }
                            })
                            localStorage.setItem("chatInputRecord", JSON.stringify(local))

                            showSendBtn();

                            //滚动条到最底部(还有其他方法吗？)
                            document.getElementById("msg_list").scrollTop = msgList.scrollHeight + msgList.offsetHeight;
                            setTimeout(function () {
                                keyy += '#';
                                var elee = $(keyy);
                                copyClipboard(elee);
                            }, 0);

                        } else {
                            mui.toast(data.errorMsg);
                        }

                    } else {
                        mui.toast("系统异常");
                    }
                    $(".qjs-backdrop").hide();

                },
                error: function (e) {
                    sendFlag = true;
                    $(".qjs-backdrop").hide();
                    mui.toast("网络异常");
                }
            });

        });

        /*]]>*/

        $("#upImage").on("tap", function () {
            if (!imageLock) {
                return !1;
            }
            if (wxAuth) {
                //发送tup
                wx.checkJsApi({
                    jsApiList: ['chooseImage', 'uploadImage', 'previewImage', 'getLocalImgData'],// 需要检测的JS接口列表，所有JS接口列表见附录2,
                    success: function (res) {
                        // 以键值对的形式返回，可用的api值true，不可用为false
                        // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
                        var check = res.checkResult.chooseImage;
                        if (check) {
                            wx.chooseImage({
                                count: 1, // 默认9
                                sizeType: ['original', 'compressed'],  // 可以指定是原图还是压缩图，默认二者都有
                                sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                                success: function (res) {
                                    var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                                    wx.uploadImage({
                                        localId: localIds[0],
                                        isShowProgressTips: 1,
                                        success: function (res) {
                                            sendImage(localIds[0], res.serverId);
                                        },
                                        fail: function (res) {
                                            mui.toast("发送图片失败");
                                        }
                                    });
                                },
                                fail: function (res) {
                                    mui.toast("该版本不支持发送图片");
                                }
                            });

                        } else {
                            mui.toast("该版本不支持发送图片");
                        }
                    }
                });
            } else {
                mui.toast("该版本不支持发送图片");
            }
        });

    });

    //显示或隐藏发送按钮
    function showSendBtn() {
        if ($(".Emoji").css('display') != 'none') {
            return !1;
        }
        //处理是否显示发送消息按钮
        if ($("#msg_text").val().trim()) {
            $("#sendMessage").removeClass("mui-hidden");
            $(".footer-right .chat-icon-add-more").addClass("mui-hidden");
            $('.simple').show();
            $('#footer').css('bottom', '8.533333333333333rem');
            $('.im-chat-main').css('paddingBottom', '11.093333333333334rem');
        } else {
            $("#sendMessage").addClass("mui-hidden");
            $(".footer-right .chat-icon-add-more").removeClass("mui-hidden");
            $('.simple').hide();
            $(".Emoji").hide();
            $('#footer').css('bottom', '0');
            $('.im-chat-main').css('paddingBottom', '2.1333333333333333rem');
            // setTimeout(function(){
            //     isOpenOften = true;
            // },1000)
        }
        $(".more-content").hide();

    }
    //在焦点处插入内容
    function focusInsert(obj, str) {
        var result, val = obj.value;
        obj.focus();
        if (document.selection) { //ie
            result = document.selection.createRange();
            document.selection.empty();
            result.text = str;
        } else {
            result = [
                val.substring(0, obj.selectionStart),
                str,
                val.substr(obj.selectionEnd)
            ];
            obj.focus();
            obj.value = result.join('');
        }
    }

    /*<![CDATA[*/
    //转换内容
    function imContent(content) {
        //支持的html标签
        var html = function (end) {
            return new RegExp('\\n*\\[' + (end || '') + '(pre|div|p|table|thead|th|tbody|tr|td|ul|li|ol|li|dl|dt|dd|h2|h3|h4|h5)([\\s\\S]*?)\\]\\n*', 'g');
        };
        content = (content || '').replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
            .replace(/face\[([^\s\[\]]+?)\]/g, function (face) {  //转义表情
                var alt = face.replace(/^face/g, '');
                return '<img alt="' + alt + '" title="' + alt + '" src="' + faces[alt] + '">';
            }).replace(/a\([\s\S]+?\)\[[\s\S]*?\]/g, function (str) { //转义链接
                var href = (str.match(/a\(([\s\S]+?)\)\[/) || [])[1];
                var text = (str.match(/\)\[([\s\S]*?)\]/) || [])[1];
                if (!href)
                    return str;
                return '<a href="' + href + '" target="_blank">' + (text || href) + '</a>';
            }).replace(html(), '\<$1 $2\>').replace(html('/'), '\</$1\>') //转移代码
            .replace(/\n/g, '<br>') //转义换行
        return content;
    }
    /**
     * 获取当前时间
     */
    function getNowFormatDate() {
        //var time = new Date().format("yyyy-MM-dd HH:mm:ss");   
        var hours = new Date().getHours();
        var minutes = new Date().getMinutes();
        var time = hours + ':' + (minutes >= 9 ? minutes : '0' + minutes)
        return time;
    }
    /*]]>*/


    //weixin
    function weixin() {
        wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            beta: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: result.jsAuth.appId, // 必填，企业号的唯一标识，此处填写企业号corpid
            timestamp: result.jsAuth.timestamp, // 必填，生成签名的时间戳
            nonceStr: result.jsAuth.nonceStr, // 必填，生成签名的随机串
            signature: result.jsAuth.signature,// 必填，签名，见附录1
            jsApiList: ['chooseImage', 'uploadImage', 'getLocalImgData'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        });
        wx.error(function (res) {
            console.log("wx:error" + JSON.stringify(res));
            wxAuth = false;
        });
        wx.ready(function () {
            wxAuth = true;
            wx.hideOptionMenu();
        });
    }
    // /*<![CDATA[*/ 请求聊天记录
    function addChat(currPage, sizePage, code, id) {
        var chatId;
        if (result.list) {
            if (result.list[0].time) {
                chatId = result.list[1].id;
            } else {
                chatId = result.list[0].id;
            }
        }
        var lsttt = sessionStorage.getItem('ssssssss12');
        if (!lsttt) {
            lsttt = null;
        } else {
            lsttt = parseFloat(lsttt);
        }
        $.ajax({
            type: "post",
            dataType: "json",
            traditional: true,
            data: { pageCurrent: currPage, pageSize: sizePage, ownerCode: code, userId: id, chatId: chatId, lastTime: lsttt },
            async: false,
            url: "/chat/wx/wx_chat_talk",
            success: function (data, textStatus) {
                messFlag = true;
                if (data) {
                    if (data.returnFlag == 1) {
                        result.list = data.data
                        // result.list = []
                        // data.data.forEach(function(v, i){
                        //     if(v.time){
                        //         result.list.unshift(v)
                        //     }else{
                        //         if(lastTime < v.lastTime){
                        //             lastTime = v.lastTime
                        //         }
                        //         result.list.push(v)
                        //     }
                        // })
                        var len = result.list.length;
                        for (var i = 0; i < len; i++) {
                            var content = result.list[i].content;
                            if (checkImage(content)) {
                                var reg = mess_reg;
                                content = content.replace(reg, "");
                                result.list[i].content = content;
                                result.list[i].imgFlag = 1;
                            }
                            if (msgIdFlag) {
                                try {
                                    var msg = result.list[i].msgId;
                                } catch (e) {
                                    msg = null;
                                }
                                if (msg) {
                                    msgId.push(msg);
                                }

                            }
                            var cruntT = result.list[i].lastTime
                            // 更新最一条记录的时间
                            if (lastTime < cruntT) {
                                lastTime = cruntT
                            }

                            if (!isLastTime && cruntT) {
                                // debugger;
                                isLastTime = true;
                                sessionStorage.setItem('ssssssss12', result.list[i]['lastTime'])
                                // lsTimerrrrrr = {"lsTime":result.list[i]['lastTime']};
                                id = result.list[i]['id'];
                            }


                        }
                        isLastTime = false;
                        msgIdFlag = false;
                        var html = template('list', result);
                        jQuery("#msg_list").prepend(html);
                        // setTimeout(function(){window.scrollTo(0, document.body.scrollHeight);},500)
                        //msgList.insertAdjacentHTML("afterBegin",html);
                        //滚动条到最底部(还有其他方法吗？)
                        //   document.getElementById("msg_list").scrollTop = msgList.scrollHeight + msgList.offsetHeight;

                        setTimeout(function () {
                            // 聊天列表单条复制功能
                            $('.im-chat-text').each(function (i, v) {
                                $(v).unbind('tap')
                                var ele = $(v).children('span')[0];
                                copyClipboard(ele);
                            })
                        }, 0);

                    } else {
                        mui.toast(data.errorMsg);
                    }





                }
            },
            error: function (e) {
                messFlag = true;
                mui.toast("网络异常");
            }
        });
    }
    /*]]>*/
    function sendImage(locId, serId) {
        $(".qjs-backdrop").show();
        $.ajax({
            type: "post",
            dataType: "json",
            traditional: true,
            data: { userId: id, ownerCode: code, serId: serId },
            async: true,
            url: "/chat/wx/wx_sendimage",
            success: function (data, textStatus) {
                $(".qjs-backdrop").hide();
                if (data) {
                    if (data.returnFlag == 1) {
                        if (checkWkWebView()) {
                            //wkwebview
                            wx.getLocalImgData({
                                localId: locId, // 图片的localID
                                success: function (res) {
                                    var localData = res.localData; // localData是图片的base64数据，可以用img标签显示
                                    var html = '<li class="im-chat-mine">' +
                                        '<div class="im-chat-user">' +
                                        '<img src="' + result.user.iconsPhoto + '"/>' +
                                        // '<cite><i>' + getNowFormatDate() + '</i>' + result.user.weixinName + '</cite>' +
                                        '</div>' +
                                        '<div class="im-chat-text">' + '<img class="previewImage" src="' + localData + '"/>' + '</div>' +
                                        '</li>';

                                    //追加内容
                                    msgList.insertAdjacentHTML('beforeEnd', html);

                                    //清空
                                    $(".more-content").hide();
                                    $("footer").css("bottom", "0");
                                    $(".im-chat-main").css("padding-bottom", "2.1333333333333333rem");

                                    //滚动条到最底部(还有其他方法吗？)
                                    document.getElementById("msg_list").scrollTop = msgList.scrollHeight + msgList.offsetHeight;
                                    bindImage(".im-chat-text .previewImage");

                                },
                                fail: function (res) {
                                    //   alert(JSON.stringify(res));
                                },
                                compvare: function (res) {
                                    //  alert(JSON.stringify(res));
                                }
                            });
                        } else {
                            //演示就直接拼接了
                            var html = '<li class="im-chat-mine">' +
                                '<div class="im-chat-user">' +
                                '<img src="' + result.user.iconsPhoto + '"/>' +
                                // '<cite><i>' + getNowFormatDate() + '</i>' + result.user.weixinName + '</cite>' +
                                '</div>' +
                                '<div class="im-chat-text">' + '<img class="previewImage" src="' + locId + '"/>' + '</div>' +
                                '</li>';
                            //追加内容
                            msgList.insertAdjacentHTML('beforeEnd', html);

                            //清空
                            $(".more-content").hide();
                            $("footer").css("bottom", "0");
                            $(".im-chat-main").css("padding-bottom", "2.1333333333333333rem");

                            //滚动条到最底部(还有其他方法吗？)
                            document.getElementById("msg_list").scrollTop = msgList.scrollHeight + msgList.offsetHeight;
                            bindImage(".im-chat-text .previewImage");
                        }

                    } else {
                        mui.toast(data.errorMsg);
                    }

                }
            },
            error: function (e) {
                $(".qjs-backdrop").hide();
                mui.toast("请求失败");
            }
        });
    }
    /*<![CDATA[*/
    function upload() {
        var length = images.localId.length;
        if (length == 0) {
            return;
        }
        for (var i = 0; i < length; i++) {
            var id = images.localId.shift();
            wx.uploadImage({
                localId: id,
                isShowProgressTips: 1,
                success: function (res) {
                    images.serverId.push(res.serverId);
                    mui.toast(JSON.stringify(images));
                },
                fail: function (res) {
                    mui.toast(JSON.stringify(res));
                }
            });
        }

    }
    function bindImage(_elements) {
        $(_elements).unbind("tap");
        $(_elements).on("tap", function (e) {
            //阻止事件冒泡
            e.stopPropagation();
            var imageUrl = e.currentTarget.currentSrc;
            //var imageUrl="http://www.qqpk.cn/Article/UploadFiles/oumei/10.jpg";
            if (typeof (imageUrl) == "undefined") {
                imageUrl = $(this).attr('src');
            }
            var imgArray = [];
            imgArray.push(imageUrl);
            wx.previewImage({
                current: imageUrl, // 当前显示图片的http链接
                urls: imgArray // 需要预览的图片http链接列表
            });
        })
    }
/*]]>*/

</script>
<script type="text/javascript">
    var JIM = new JMessage({ debug: false });
    $(function () {
        function init() {
            JIM.init({
                "appkey": result.auth.appkey,
                "random_str": result.auth.random_str,
                "signature": result.auth.signature,
                "timestamp": result.auth.timestamp
            }).onSuccess(function (data) {
                console.log('success:' + "JIM.init");
                login();
            }).onFail(function (data) {
                console.log('error:' + JSON.stringify(data));
            });
        }
        /*<![CDATA[*/
        function login() {   // 消息接收
            JIM.login({
                'username': result.user.imessageCode,
                'password': '123456'
            }).onSuccess(function (data) {
                console.log('success:' + "JIM.login");
                JIM.onMsgReceive(function (data) {
                    var ctime = data.messages[0].ctime;
                    if (!ctime) {
                        ctime = data.messages[0].ctime_ms;
                    }
                    var mmsgid = data.messages[0].msgId

                    // var t = parseInt(lastTime) - parseInt(ctime);
                    var formId = data.messages[0].content.from_id;
                    var form_msgId = parseInt(data.messages[0].msg_id);
                    if (formId != result.customer.ownerCode) {
                        return;
                    }
                    if (msgId) {
                        msgId.sort();
                        var len = msgId.length;
                        for (var i = 0; i < len; i++) {
                            if (form_msgId == msgId[i]) {
                                return;
                            }
                        }
                        var m = msgId[0];
                        if (!form_msgId > m) {
                            return;
                        }
                        msgId.shift();
                        msgId.push(form_msgId);
                    } else {
                        if (t >= 0) {
                            return;
                        }
                    }
                    var image;
                    if (!result.customer.ownerIcon) {
                        image = '/chat/wxchat/static/images/demo6.png';
                    } else {
                        image = result.customer.ownerIcon;
                    }


                    var sub = parseInt(ctime) - lastTime;
                    var li = "";
                    var currentTime = getNowFormatDate();
                    if (sub > 300000) {
                        li = '<div class="recording_time"><span>' + currentTime + '</span></div>';
                        $.ajax({
                            type: "post",
                            dataType: "json",
                            traditional: true,
                            data: { msgId: mmsgid },
                            async: true,
                            url: "/chat/wx/wx_addDateShow",
                            success: function (result) {
                            },
                        })
                    }
                    var keyy = "df" + sub
                    if (data) {
                        var content = data.messages[0].content.msg_body.text;
                        if (checkImage(content)) {
                            var reg = mess_reg;
                            content = content.replace(reg, "");
                            li += '<li class="lili"><div class="im-chat-user"><img src="' + image + '"/></div><div class="im-chat-text">' + '<img class="previewImage" src="' + content + '"/>' + '</div></li>';
                        } else {
                            li += '<li class="lili"><div class="im-chat-user"><img src="' + image + '"/></div><div class="im-chat-text"><span id=' + keyy + '>' + content + '</span></div></li>';
                        }
                        $('#msg_list').append(li);
                        document.getElementById("msg_list").scrollTop = msgList.scrollHeight + msgList.offsetHeight;
                        bindImage(".im-chat-text .previewImage");

                        setTimeout(function () {
                            keyy += '#';
                            var ellle = $(keyy);
                            copyClipboard(ellle);
                        }, 0)

                        lastTime = (new Date()).getTime();

                    }


                });
                JIM.onEventNotification(function (data) {
                    console.log('event_receive: ' + JSON.stringify(data));
                });
            }).onFail(function (data) {
                console.log('error:' + JSON.stringify(data));
            }).onTimeout(function (data) {
                console.log('timeout:' + JSON.stringify(data));
            });
        }
        /*]]>*/
        init();
        myStorage.setItem(code, 1);
    })

    // 定位光标
    function focused(e) {
        var textDom = document.getElementById("msg_text")
        if (textDom.setSelectionRange) {
            textDom.focus();
            textDom.setSelectionRange(cursorPositon, cursorPositon);
        } else if (textDom.createTextRange) {
            var range = textDom.createTextRange();
            range.collapse(true);
            range.moveEnd('character', cursorPositon);
            range.moveStart('character', cursorPositon);
            range.select();
        }
        // window.scrollTo(0, document.body.scrollHeight);
    }
    // 常见对白/内容库打开关闭
    function openFilter() {
        if ($('.simple').css('display') === 'none') {
            $('.simple').show();
            $('.Emoji').hide();
            $(".more-content").hide();
            $('#footer').css('bottom', '8.533333333333333rem');
            $('.im-chat-main').css('paddingBottom', '11.093333333333334rem');
            // 设置初始化状态
            if ($('.simple_often').hasClass('simple_check')) {
                $('.simple_many').removeClass('simple_check');
                $('.often_list').show()
                $('.many_list').hide()
            } else if ($('.simple_many').hasClass('simple_check')) {
                $('.many_list').show()
                $('.often_list').hide();
            } else {
                $('.simple_often').addClass('simple_check');
                $('.often_list').show()
                $('.many_list').hide()
            }

            // 筛选常见对白
            if ($('.often_list').css('display') != 'none') {
                var reg = $("#msg_text").val().trim();
                var arr = [];
                $.each(memoryData, function (i, v) {
                    if (v.content.indexOf(reg) != -1) {
                        arr.push(v)
                    }
                })
                oftenData.list = arr
            } else {
                oftenData.list = memoryData
            }
            document.getElementById('often_list').innerHTML = template('oftenList', oftenData);

            // 常见对白 click
            oftenAddClick()
            // isOpenOften = false
            // window.scrollTo(0, document.body.scrollHeight);
        } else {
            $('.simple').hide();
            $(".more-content").hide();
            $(".Emoji").hide();
            $('#footer').css('bottom', '0');
            $('.im-chat-main').css('paddingBottom', '2.1333333333333333rem');
            // isOpenOften = true;
        }

        // document.getElementById("msg_list").scrollTop = msgList.scrollHeight + msgList.offsetHeight;

    }


    // 缓存聊天记录
    function setLocal() {
        var str = $("#msg_text").val().trim();
        var getLocal = localStorage.getItem('chatInputRecord');
        var obj = { code: sessionObjCode, content: str };
        var isAppear = false;
        getLocal = getLocal ? JSON.parse(getLocal) : []
        $.each(getLocal, function (i, v) {
            if (v.code === sessionObjCode) {
                getLocal[i] = obj;
                isAppear = true;
            }
        })
        if (!isAppear) {
            getLocal.push(obj);
        }
        localStorage.setItem("chatInputRecord", JSON.stringify(getLocal));

        if (str === 'clear') {
            localStorage.removeItem('chatInputRecord')
            alert("草稿缓存已清除！")
        }
    }

    // 读取缓存
    function getLocal(sessionObjCode) {
        var loca = localStorage.getItem('chatInputRecord');
        var setD = [];
        loca = loca ? JSON.parse(loca) : [];

        $.each(loca, function (i, v) {
            if (v.content.length) {
                // imageLock = true;
                // mui.toast(sessionObjCode);
                if (v.code === sessionObjCode) {
                    $("#msg_text").val(v.content);
                    showSendBtn();
                    openFilter();
                }
            }
            setD.push(v)
        })
        localStorage.setItem("chatInputRecord", JSON.stringify(setD))
    }

    // 复制功能
    function copyClipboard(element) {
        if (!element) { return };
        $(element).unbind('tap');
        $(element).on('tap', function (event) {
            $('.masgCopy').siblings('span').css('pointerEvents', 'auto');
            $('.masgCopy').remove();

            $(this).css('pointerEvents', 'none');
            var coypVal = ""
            coypVal = this.innerText;
            $(this).parent().append('<button class="masgCopy" data-clipboard-text="' + coypVal + '" style="pointerEvents:none">复制</button>');

            var node = $(this).siblings('button')[0];

            setTimeout((function (n, c) {
                return function () {
                    var clipboard = new Clipboard(n, {
                        text: function () {
                            return '' + c;
                        }
                    });
                    clipboard.on('success', function (e) {
                        imageLock = true;
                        mui.toast("复制成功！");
                        $('.masgCopy').siblings('span').css('pointerEvents', 'auto');
                        $('.masgCopy').remove();

                    });
                    clipboard.on('error', function (e) {
                        imageLock = true;
                        mui.toast("仅支持IOS 10及以上版本, 请升级后体验！");
                        $('.masgCopy').siblings('span').css('pointerEvents', 'auto');
                        $('.masgCopy').remove();
                    });


                }


            })(node, coypVal), 400);


        })

        $(element).parents('div').on('tap', function (e) {
            // $(this).css('pointerEvents','none');
            var docE = $(e.target);
            console.log()
            if (docE.attr('class') == "im-chat-mine" || docE.attr('class') == "lili") {
                $('.masgCopy').siblings('span').css('pointerEvents', 'auto');
                $('.masgCopy').remove();
            }
        })


    }

    // 常见对白 click
    function oftenAddClick() {
        $('.often_list > p').each(function (i, v) {
            $(v).unbind('tap')
            $(v).on('tap', function (e) {
                e.stopPropagation()
                var msgVal = $('#msg_text').val().trim();
                var id = $(this).children('span')[0].getAttribute('data-id')
                $('#msg_text').val($(this).children('span')[0].innerText)
                cursorPositon = $('#msg_text').val().length;
                // focused()
                $('.often_list > p').each(function (index, value) {
                    $(value).removeClass('simple_check')
                })
                $(this).addClass('simple_check')
                $("#sendMessage").removeClass("mui-hidden");
                $(".footer-right .chat-icon-add-more").addClass("mui-hidden");
                setLocal()
                // 更新常见对白频次
                $.ajax({
                    type: "post",
                    dataType: "json",
                    traditional: true,
                    data: { id: id },
                    async: true,
                    url: "/chat/wx/updateDialogueTimes",
                    success: function (result) {
                        console.log(result, '================')
                    },
                    error: function (e) {
                        imageLock = true;
                        mui.toast("网络异常");
                    }
                });
            })
        })
    }

    // 常见内容库 一级 click
    function manyAddClick() {
        $('.many_one').each(function (i, v) {
            // 方法
            $(v).children('p').unbind('tap')
            $(v).children('p').on('tap', function (event) {
                event.stopPropagation();
                var oneEle = $(this).parents('.many_one').children('.many_two');
                var msgVal = $('#msg_text').val();
                // $('.many_two').hide();
                // 一级状态clear
                $('.many_one').each(function (index, value) {
                    var tempEle = $(value).children('p')[0]
                    $(tempEle).removeClass('simple_check')
                    // 二级状态clear
                    var clearTwoEle = $(tempEle).next().children('p')[0]
                    $(clearTwoEle).removeClass('simple_check')
                    // $(value).children('.many_two').hide()
                    //console.log($(value).children('p').children('.many_one_arrow'))
                    $(value).children('p').children('.many_one_arrow')[0].innerHTML = "&#xe603;"

                    // 三级状态clear
                    var clearThreeEle = $(clearTwoEle).next().children('p')[0]
                    $(clearThreeEle).removeClass('simple_check')

                    // 三级状态隐藏
                    // $('.many_three').hide();

                })
                // 一级状态add
                $(this).addClass('simple_check')
                // debugger;
                if (oneEle.length) {
                    if ($(oneEle).css('display') != 'none') {
                        $(oneEle).hide()
                        $(this).children('.many_one_arrow')[0].innerHTML = "&#xe603;"
                    } else {
                        $(oneEle).show()
                        //$(oneEle).children('.many_three').hide()
                        $(this).children('.many_one_arrow')[0].innerHTML = "&#xe64b;"
                    }
                    // 二级事件绑定
                    manyTwoAddClick();
                } else {
                    // $('#msg_text').val(msgVal + $(this).children('span')[0].innerText)
                    // cursorPositon = $('#msg_text').val().length;
                    // 聊天缓存
                    // setLocal()
                }

                $(document).css('pointer-events', 'none');
                setTimeout(function () {
                    $(document).css('pointer-events', 'auto');
                }, 400);

            })
        })
    }

    // 常见内容库 三级 click
    function manyThreeAddClick() {
        $('.many_three>p').unbind('tap');
        $('.many_three>p').on('tap', function (e) {
            var msgVal = $('#msg_text').val();
            $('#msg_text').val($(this).children('span')[0].innerText)
            cursorPositon = $('#msg_text').val().length;

            // 三级状态add
            $('.many_three').children('p').removeClass('simple_check');
            $(this).addClass('simple_check');
            // 隐藏其他二级
            $('.many_two').hide();
            var isss = $('.many_one').children('p').children('i');
            $.each(isss, function (i, v) {
                this.innerHTML = "&#xe603;";
            })
            $(this).parent('.many_three').show();
            $(this).parent('.many_three').parent('.many_two').show();
            $(this).parent('.many_three').parent('.many_two').parent('.many_one').show();
            $(this).parent('.many_three').parent('.many_two').parent('.many_one').children('p').children('i')[0].innerHTML = "&#xe64b;"

            // 更新二级
            $('.many_two').children('p').removeClass('simple_check');
            $(this).parent('.many_three').siblings('p').addClass('simple_check');
            // 更新一级
            $('.many_one').children('p').removeClass('simple_check');
            $(this).parent('.many_three').parent('.many_two').parent('.many_one').children('p').addClass('simple_check');
            // 聊天缓存
            setLocal();
            showSendBtn();

            $(document).css('pointer-events', 'none');
            setTimeout(function () {
                $(document).css('pointer-events', 'auto');
            }, 400);
            e.stopPropagation();
        });
    }

    // 常见内容库 二级 click
    function manyTwoAddClick() {
        $('.many_two>p').unbind('tap');
        $('.many_two>p').on('tap', function (ev) {
            ev.stopPropagation();
            var twoEle = $(this).parent().children('.many_three');

            var msgVal = $('#msg_text').val()
            // 三级级状态
            if (twoEle.length) {
                if ($(twoEle).css('display') != 'none') {
                    $(twoEle).hide()
                } else {
                    $(twoEle).show()
                }
                // 三级事件绑定
                manyThreeAddClick();
            } else {
                // $('#msg_text').val(msgVal + $(this).children('span')[0].innerText)
                // cursorPositon = $('#msg_text').val().length;

                // 聊天缓存
                // setLocal()
            }

            // 更新二级状态
            $('.many_two').children('p').removeClass('simple_check');
            $(this).addClass('simple_check');

            // 更新一级状态
            $('.many_one').children('p').removeClass('simple_check');
            $(this).parent('.many_two').parent('.many_one').children('p').addClass('simple_check');

            // 更新三级状态
            $('.many_three').children('p').removeClass('simple_check');

            $(document).css('pointer-events', 'none');
            setTimeout(function () {
                $(document).css('pointer-events', 'auto');
            }, 400);
        });
    }


    // 筛选常见内容库
    function filterMany() {

        var reg = $('#msg_text').val();
        var arr = [];
        var current = [0, 0];
        var p = o = l = i = j = 0, temp, tem, te, obj, len;

        if ($('.many_list').css('display') != 'none') {
            arr = [];
            // 数据筛选
            // alert(JSON.stringify(manyListData));
            for (p = 0; (temp = manyListData[p]) != undefined; p++) {
                for (o = 0; (tem = temp.children[o]) != undefined; o++) {
                    if(tem['contents'] == undefined){
                        continue;
                    }
                    for (l = 0; (te = tem.contents[l]) != undefined; l++) {
                        obj = {
                            firstName: temp.firstName,
                            children: [
                                {
                                    contents: [te],
                                    secondName: tem.secondName
                                }
                            ]
                        };
                        if (te.indexOf(reg) != -1) {
                            // arr.push(obj);
                            // debugger;
                            if (!arr.length) {        // 初始化
                                arr.push(obj);
                            } else if (current[1] == o) {    // 内容整合
                                if (current[0] == p) {
                                    arr[p].children[o].contents.push(te);
                                } else {
                                    arr.push(obj);
                                }
                            } else if (current[0] == p) {    // 二级标签整合
                                arr[p].children.push({
                                    contents: [te],
                                    secondName: tem.secondName
                                });
                            } else {      // 一级标签整合
                                arr.push(obj);
                            }
                            // 更新下标
                            current[0] = p;
                            current[1] = o;
                        }
                    }
                }
            }

            // // 一级标签整合
            // for(i = 0; (temp = arr[i]) != undefined; i++){
            //     if(arr[i+1]){
            //         if(temp.firstName === arr[i+1].firstName){
            //             arr[i].children.push(arr[i+1].children[0]);
            //             arr.splice(i+1,1);
            //             --i;
            //         }
            //     }
            // }
            // // 二级标签整合
            // for(k = 0; (temp = arr[k]) != undefined; k++){
            //     for(j = 0; (te = temp.children[j]) != undefined; j++){
            //         if(temp.children[j+1]){
            //             if(te.secondName === temp.children[j+1].secondName){
            //                 arr[k].children[j].contents.push(arr[k].children[j+1].contents[0]);
            //                 arr[k].children.splice(j+1,1);
            //                 --j;
            //             }
            //         }
            //     }
            // }

            manyData = { list: arr };
            // alert(JSON.stringify(arr));
        } else {

            manyData = { list:manyListData };
        }
        // 页面渲染
        document.getElementById('many_list').innerHTML = template('manyList', manyData);

        // 展示结果
        // alert(2);
        $('.many_two').show();
        $('.many_three').show();
        $('.many_one').each(function (index, value) {
            $(value).children('p').children('.many_one_arrow')[0].innerHTML = "&#xe64b;"
        });

        // 一级标签事件绑定
        manyAddClick();

        // 二级标签事件绑定
        manyTwoAddClick();

        // 三级内容事件绑定
        manyThreeAddClick();
    }

    // 筛选常见对白
    function filterOften() {
        var reg = $('#msg_text').val();
        var arr = [];
        if ($('.often_list').css('display') != 'none') {
            arr = [];
            $.each(memoryData, function (i, v) {
                if (v.content.indexOf(reg) != -1) {
                    arr.push(v)
                }
            })
            oftenData.list = arr
        } else {
            oftenData.list = memoryData
        }
        // 页面渲染
        document.getElementById('often_list').innerHTML = template('oftenList', oftenData);
        // 事件绑定
        oftenAddClick();
    }





    var emojiList = [
        "😩", "😲", "😞", "😵", "😰", "😒", "😍", "😤", "😜", "😝", "😋", "😘", "😚", "😷", "😳", "😃", "😆", "😁", "😂", "😄", "😢", "😭", "😨", "😣", "😡", "😌", "😖", "😔", "😱", "😪", "😏", "😓", "😥", "😫", "😉", "😺", "😸", "😹", "😽", "😻", "😿", "😼", "🙀", "🙋", "🙌", "🙍", "🙏", "🔥", "🎁", "🎄", "🎅", "🎈", "🎉", "👮", "👱", "👲", "👳", "👴", "👵", "👶", "👷", "👸", "👯", "👻", "👼", "👽", "👾", "👿", "💀", "💂", "💃", "🌻", "🌴", "🌵", "🌾", "🍎", "🍊", "🍓", "👀", "👂", "👃", "👄", "👅", "💅", "👦", "👧", "👨", "👩", "👫", "🎍", "🎎", "🎓", "🎏", "🎐", "🎃", "📞", "📱", "📲", "📠", "💻", "💽", "💾", "💿", "📀", "🎵", "🎶", "🎼", "💜", "💝", "💢", "💤", "💦", "💨", "💩", "💪", "✨", "🔔", "✊", "👊", "👍", "☝", "👆", "👇", "👈", "👉", "👋", "👏", "👌", "👎", "👐", "🌀", "🌂", "🌙", "🌟", "🍀", "🌷", "🌱", "🍁", "🌸", "🌹", "🍂", "🍃", "🌺"
    ]
    var line = []
    var newSort = { list: [] }

    $.each(emojiList, function (i, v) {
        line.push("<span>" + v + "</span>")
        if ((i + 1) % 35 == 0 || i === emojiList.length - 1) {
            var join = line.join("") + '<i class="gtmc_chat backspace" alt="退格">&#xe659;</i>'
            newSort.list.push(join)
            line = []
        }
    })
    // 添加表情
    var listEle = $('.mui-slider-item')
    $.each(listEle, function (i, v) {
        this.innerHTML = newSort.list[i]
    })

    // 打开表情包
    $('.emoticon').on('tap', function () {
        if ($('.Emoji').css('display') === 'none') {
            $('.Emoji').show();
            $(".more-content").hide();
            $(".simple").hide();
            $('#footer').css('bottom', '8.533333333333333rem');
            $('.im-chat-main').css('paddingBottom', '11.093333333333334rem');
        } else {
            $('.Emoji').hide();
            $(".more-content").hide();
            $(".simple").hide();
            $('#footer').css('bottom', '0');
            $('.im-chat-main').css('paddingBottom', '2.1333333333333333rem');
        }

        document.getElementById("msg_list").scrollTop = msgList.scrollHeight + msgList.offsetHeight;
    })

    // 点击单个表情
    $('.Emoji .mui-slider-item>span').on('tap', function () {
        var str = $('#msg_text').val()
        var Em = str.slice(0, cursorPositon) + this.innerHTML + str.slice(cursorPositon, str.length)
        cursorPositon += 2;
        $('#msg_text').val(Em);
        $("#sendMessage").removeClass("mui-hidden");
        $(".footer-right .chat-icon-add-more").addClass("mui-hidden");
        var obj = document.getElementById("msg_text");
        obj.scrollTop = obj.scrollHeight;
        setLocal();
        // setTimeout(function(){focused();},0)
        $("#footer").unbind("tap");
        $("#footer").on("tap", function (event) {
            var sendMsgBtn = $(event.target);
            if (sendMsgBtn.attr('id') == 'footer') {
                $("#sendMessage").trigger('tap');
            }
        })

        // window.scrollTo(0, document.body.scrollHeight);
    })

    // 表情退格
    setTimeout(function () {
        $('.backspace').on('tap', function () {
            var str = $('#msg_text').val()
            var len = str.length
            var lastSign = str.slice(cursorPositon - 1, cursorPositon).charCodeAt(0).toString(16)
            var step = lastSign.length === 4 ? 2 : 1

            if (cursorPositon != 0) {
                var msg = cursorPositon === str.length
                    ? str.slice(0, len - step)
                    : str.slice(0, cursorPositon - step) + str.slice(cursorPositon, len)
                $('#msg_text').val(msg)
                cursorPositon -= step
            }
            if (!$('#msg_text').val()) {
                showSendBtn();
            }
        })
    }, 0)

    // 打开筛选
    $('.dialogue').on('tap', openFilter);


 

    // 常见对白/内容库tab栏切换
    $('.simple_tit>span').unbind('tap')
    $('.simple_tit>span').on('tap', function (ev) {
        $(this).addClass('simple_check')
        if ($(this).hasClass('simple_often')) {     // 常见对白
            $('.simple_many').removeClass('simple_check')
            $('.often_list').show();
            $('.many_list').hide();
            // 常见对白筛选
            filterOften();
        } else {    // 常见内容库
            $('.simple_often').removeClass('simple_check')
            $('.many_list').show();
            $('.often_list').hide();
            $('.many_one_bottom').hide();
            // 常见内容筛选
            filterMany();
        }
        ev.stopPropagation();
    });



</script>



</html>